package com.fare.taluo.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;


public class Pinying4jUtil {

		public static HanyuPinyinOutputFormat format = null;
		private static String[] pinyin=null;


		/**
		 * 转换单个字符
		 * @param c 
		 * @return
		 */
		public static String trans2Char(char c){
			if(null== format){
				format = new HanyuPinyinOutputFormat();
				format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
			}
			try{
				pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
			}catch (BadHanyuPinyinOutputFormatCombination e){
				e.printStackTrace();
			}
			// 如果c不是汉字，toHanyuPinyinStringArray会返回null
			// 只取一个发音，如果是多音字，仅取第一个发音
			return (pinyin == null) ? null : pinyin[0];
		}
		
		/**
		 * 转换成全拼+首字母
		 * @param str
		 * @return
		 */
		public static String trans2Full(String str){
			StringBuffer sb = new StringBuffer(trans2QuanPin(str));
			return sb.append(trans2HeadChar(str)).toString();
		}

		/**
		 * 转换一段字符串为全拼
		 * @param str
		 * @return
		 */
		public static String trans2QuanPin(String str){
			if(null==str)return null;
			StringBuffer sb = new StringBuffer();
			String tempPinyin = null;
			if(null== format){
				format = new HanyuPinyinOutputFormat();
				format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
			}
			for (int i = 0; i < str.length(); i++){
				tempPinyin = trans2Char(str.charAt(i));
				if (tempPinyin == null){ // 如果str.charAt(i)非汉字，则保持原样
					sb.append(str.charAt(i));
				}else{
					sb.append(tempPinyin);
				}
			}
			return sb.toString();
		}

		/**
		 * 转换成 汉字首字母
		 * @param str
		 * @return
		 */
		public static String trans2HeadChar(String str){
			if(null==str)return null;
			if(null== format){
				format = new HanyuPinyinOutputFormat();
				format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
			}
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < str.length(); i++) {
				String tempPinyin[] = PinyinHelper.toHanyuPinyinStringArray(str.charAt(i));
				if (tempPinyin == null){ // 如果str.charAt(i)非汉字，则保持原样
					sb.append(str.charAt(i));
				}else{// 提取汉字的首字母
					sb.append(tempPinyin[0].charAt(0));
				}
			}
			return sb.toString();
		}
	

}
